#include "./AddPlayer.h"
#include "../Core/Player.h"

using namespace Commands;

AddPlayer::AddPlayer(
	unsigned char player_id,
	char secret,
	unsigned char team,
	GameLogic::Objects::GameObject::IdType object_id,
	bool is_local
) :
	player_id_( player_id )
,	secret_( secret )
,	team_( team )
,	object_id_( object_id )
,	is_local_( is_local )
{}

void AddPlayer::execute( GameLogic::Simulation* sim ) {
	Core::PlayerArray &player_array = Core::PlayerArray::getInstance();

	//tworzy id obiektu gracza:
	GameLogic::Objects::ObjectId oid = GameLogic::Objects::ObjectId( object_id_.getType(), player_id_, 0 );

	// przygotowuje strukture opisujaca gracza:
	Core::Player* player_struct = new Core::Player();
	player_struct->id = player_id_;
	player_struct->uid = secret_;
	player_struct->team = team_;

	// wpisuje gracza do tabeli graczy:
	player_array.addPlayer( player_id_, player_struct );
	if( is_local_ )
		player_array.setLocalPlayerById( player_id_ );

	//tworzy gracza na spawnpoincie:
	Data *data = new Data();
	data->time = sim->now();
	data->position = sim->getLevel()->getSpawnPoint( team_ );

	// tworzy obiekt:
	sim->updateObject( oid, data );

	// zapisuje w strukturze gracza wskazanie na kontrolowany przez niego obiekt:
	player_struct->controlled_object = sim->getGameObject( oid );
}

void AddPlayer::serialize( std::ostringstream& s ) {
	s << Network::UDPIO::PLAYER_EVENT << SEPARATOR;
	s << player_id_ << SEPARATOR;
	s << secret_ << SEPARATOR;
	s << team_ << SEPARATOR;
	s << object_id_.toNumeric() << SEPARATOR;
	s << is_local_;
}

